import fetch from 'dva/fetch';
import qs from 'query-string';
import _ from 'lodash';
import { Toast } from 'antd-mobile';
import config from './config';


function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  if (response.status === 422) {
    response.json().then((error) => {
      let message;
      if (error.errors) {
        let values = _.values(error.errors)[0];
        values = values[0].split(' ');
        message = values[values.length - 1];
      } else if (error.message) {
        message = error.message;
      }
      setTimeout(() => {
        Toast.fail(message, 3);
      }, 100);
    });
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

export default function request(url, options) {
  let opts = _.extend({
    method: 'GET',
    body: null,
    callback: null,
    params: null,
    credentials: 'include',
  }, options);

  const reqOpts = {
    method: opts.method.toLocaleLowerCase(),
    headers: {},
  };

  reqOpts.headers.Accept = 'application/json';
  reqOpts.headers.k = Math.random();
  reqOpts.headers['Content-Type'] = 'application/json';

  if (reqOpts.method === 'post' || reqOpts.method === 'put') {
    reqOpts.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  }
  if (opts.body) {
    opts.body = qs.stringify(opts.body);
  }
  let newUrl = url;

  if (/\/v6/.test(url)) {
    config.API_URL = '/api'
    newUrl = newUrl.replace(/\/v6/, '')
  }else {
    config.API_URL = '/api'
  }
  
  if (opts.params) {
    newUrl = `/${newUrl}?${qs.stringify(opts.params)}`;
  }


  opts = _.extend(opts, reqOpts);

  return fetch(`${config.API_URL}${newUrl}`, opts)
    .then(checkStatus)
    .then(parseJSON);
    // .catch((err) => {
    //   // console.log(err);
    //   return err;
    // });
}
